﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using NNS.Enumeration;
using NNS.Framework;
using NNS.UI;
using QLTB.BusinessLayer;
using QLTB.BusinessObjects;
using QLTB.Common;
using QLTB.DataAccess;
using QLTB.ThietBi.Entity;

namespace QLTB.ThietBi.UI
{
    [System.ComponentModel.ToolboxItem(false)]
    public partial class ucThietBi : MyUIBase
    {
        #region Column enum

        public enum Column
        {
            None,
            MaTB,
            TenTB,
            Lock
        }

        #endregion

        private frmDetail detail;
        private TBL_DONVI dv;
        private Column m_Column;

        public ucThietBi()
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            InitializeComponent();

            TBL_quyenBL.IgnoreError = true;
            if (!TBL_quyenBL.isTaomoi(EnumComponent.iProvider))
            {
                gbList.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
            }
            TBL_quyenBL.IgnoreError = false;

            NapInfo();

            dsThietBi.TBL_THIETBI.TBL_THIETBIRowChanged += TBL_THIETBI_TBL_THIETBIRowChanged;
            if (MyLogin.Original.toantinh)
            {
                txtDonvi.Enabled = true;
                MaDonViLookUpEdit.Enabled = true;
                colMaDonVi.Visible = true;
            }
            NotSave = false;
            Cursor.Current = current;
        }

        public bool IsFilter
        {
            get { return gbList.OptionsView.ShowAutoFilterRow; }
            set { gbList.OptionsView.ShowAutoFilterRow = value; }
        }

        private frmMain MyRibbon
        {
            get { return ParentForm as frmMain; }
        }


        private void TBL_THIETBI_TBL_THIETBIRowChanged(object sender, dsThietBi.TBL_THIETBIRowChangeEvent e)
        {
            //throw new NotImplementedException();

            if (Mode == EditMode.Load) return;
            if (Mode == EditMode.Update)
            {
                return;
            }


            if (e.Action == DataRowAction.Change)
            {
                Cursor.Current = Cursors.WaitCursor;
                //if (e.Row.RowState == DataRowState.Modified)
                {
                    if (!TBL_quyenBL.isThaydoi(EnumComponent.iEquipment))
                    {
                        Nap();
                        Cursor.Current = Cursors.Default;
                        return;
                    }
                }

                NotSave = true;

                Cursor.Current = Cursors.Default;
            }
            else if (e.Action == DataRowAction.Add)
            {
                NotSave = true;
                Save();
            }
        }

        public void Duplicate()
        {
            //throw new NotImplementedException();
            if (!Visible) return;
            var da = new TBL_THIETBIDA();
            DataTable dt = dsThietBi.TBL_THIETBI;
            if (dt.GetChanges(DataRowState.Deleted) != null)
            {
                MyBox.ShowWarning("Dữ liệu hiện tại chưa được lưu!\nVui lòng lưu lại trước khi Copy Cấu hình",
                                  "Quản lý thiết bị");
                return;
            }
            da.Duplicate((int)(dt.Rows[gbList.GetFocusedDataSourceRowIndex()]["ID"]));

            Nap();
        }

        public void EquipHistory()
        {
            Cursor.Current = Cursors.WaitCursor;

            if (!TBL_quyenBL.isXem(EnumComponent.iEquipHistory))
            {
                Cursor.Current = Cursors.Default;
                return;
            }

            if (detail == null)
            {
                detail = new frmDetail();
            }

            object _ob = gbList.GetFocusedRowCellValue(colID);
            if (_ob == null)
            {
                Cursor.Current = Cursors.Default;
                return;
            }
            TBL_THIETBI thietbi = new TBL_THIETBIDA().Get((int)_ob);
            if (thietbi == null)
            {
                Cursor.Current = Cursors.Default;
                return;
            }
            detail.ThietBi = thietbi;
            detail.Set(InfoStyle.LS);

            Cursor.Current = Cursors.Default;
            detail.ShowDialog(this);
        }

        public void Components()
        {
            Cursor.Current = Cursors.WaitCursor;

            if (!TBL_quyenBL.isXem(EnumComponent.iComponents))
            {
                Cursor.Current = Cursors.Default;
                return;
            }

            if (detail == null)
            {
                detail = new frmDetail();
            }

            object _ob = gbList.GetFocusedRowCellValue(colID);
            if (_ob == null)
            {
                Cursor.Current = Cursors.Default;
                return;
            }
            TBL_THIETBI thietbi = new TBL_THIETBIDA().Get((int)_ob);
            if (thietbi == null)
            {
                Cursor.Current = Cursors.Default;
                return;
            }

            detail.ThietBi = thietbi;
            detail.Set(InfoStyle.LK);
            Cursor.Current = Cursors.Default;
            detail.ShowDialog(this);
        }


        public void NapInfo()
        {
            //MessageBox.Show("Chao moi nguwowfi");

            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            Mode = EditMode.Load;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                tBL_DONVITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_DONVITableAdapter.Fill(dsDonVi.TBL_DONVI);
                if (txtDonvi.Text.Length == 0)
                {
                    if (dsDonVi.TBL_DONVI.Count > 0)
                    {
                        txtDonvi.EditValue = MyLogin.Original.iddonvi;
                    }
                }
                tBL_loaiTBTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_loaiTBTableAdapter.Fill(dsLoaiTB.TBL_loaiTB);

                tBL_nhasxTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_nhasxTableAdapter.Fill(dsNSX.TBL_nhasx);

                tBL_TinhtrangTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_TinhtrangTableAdapter.FillBy(dsTinhTrang.TBL_Tinhtrang);

                tBL_MucdichTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_MucdichTableAdapter.Fill(dsMucdich.TBL_Mucdich);

                Nap((int)txtDonvi.EditValue);
                txtDonvi.EditValue = MyLogin.Original.iddonvi;
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý thiết bị");
            }
            Mode = EditMode.None;
            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        private void Nap(int id)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();
            Mode = EditMode.Load;
            try
            {
                tBL_NHACUNGCAPTableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_NHACUNGCAPTableAdapter.Fill(dsNHACUNGCAP.TBL_NHACUNGCAP);

                tBL_THIETBITableAdapter.ClearBeforeFill = true;
                tBL_THIETBITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                tBL_THIETBITableAdapter.FillByNOTL(dsThietBi.TBL_THIETBI, id);

                tBL_DONVITableAdapter.Connection.ConnectionString = DbHelper.ConnectionString;
                rpDonVi.DataSource = tBL_DONVITableAdapter.GetDataBy(id);
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý thiết bị");
            }
            NotSave = false;
            Mode = EditMode.None;
            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        public void Nap()
        {
            if (txtDonvi.EditValue == null) return;
            Nap((int)txtDonvi.EditValue);
        }

        public void SelectAll()
        {
            gbList.SelectAll();
        }

        public void Copy()
        {
            gbList.CopyToClipboard();
        }

        public void ClearContext()
        {
            MaTBCalcEdit.Value = 0;
            MaNCCLookUpEdit.Text = "";
            TenTBTextEdit.Text = "";
            NguyenGiaCalcEdit.Value = 0;
            TgianSDCalcEdit.Value = 0;
            DiaChiIPTextEdit.Text = "";
            MucDichLookUpEdit.Text = "";
            TgianBHCalcEdit.Value = 0;
            DChiBHLookUpEdit.Text = "";
            DiaChiBH.Text = "";
            TinhTrangTextEdit.Text = "";
            NSXTextEdit.Text = "";
            GhiChuMemoEdit.Text = "";
        }

        public void Add()
        {
        }

        public void Cancel()
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            if (tBLTHIETBIBindingSource != null)
            {
                tBLTHIETBIBindingSource.CancelEdit();
                NotSave = false;
                NapInfo();
            }

            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        private bool Check()
        {
            dsThietBi.TBL_THIETBIDataTable dt = dsThietBi.TBL_THIETBI;
            for (int i = 0; i < dsThietBi.TBL_THIETBI.Rows.Count; i++)
            {
                DataRow dr = dsThietBi.TBL_THIETBI.Rows[i];
                if (dr.RowState != DataRowState.Deleted)
                {
                    if (dr[dt.MaDonViColumn] == DBNull.Value)
                    {
                       // MyBox.ShowWarning("Vui lòng chọn đơn vị!", "Quản lý thiết bị");
                       // dr.RowError = "Vui lòng chọn đơn vị!";
                        dr[dt.MaDonViColumn] = txtDonvi.EditValue;
                        return false;
                    }

                    if (dr[dt.MaLoaiTBColumn] == DBNull.Value)
                    {
                        MyBox.ShowWarning("Vui lòng chọn loại thiết bị!", "Quản lý thiết bị");
                        dr.RowError = "Vui lòng chọn loại thiết bị!";

                        return false;
                    }

                    if (dr[dt.NgaySuDungColumn] == DBNull.Value)
                    {
                        MyBox.ShowWarning("Vui lòng nhập ngày sử dụng!", "Quản lý thiết bị");
                        dr.RowError = "Vui lòng nhập ngày sử dụng!";
                        return false;
                    }

                    if (dr[dt.TinhTrangColumn] == DBNull.Value)
                    {
                        MyBox.ShowWarning("Vui lòng nhập tình trạng sử dụng sử dụng!", "Quản lý thiết bị");
                        dr.RowError = "Vui lòng nhập tình trạng sử dụng sử dụng!";
                        return false;
                    }
                }
            }
            return true;
        }


        public void Save()
        {
            if (!Check()) return;

            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();
            Mode = EditMode.Update;

            try
            {
                tBLTHIETBIBindingSource.EndEdit();

                for (int i = 0; i < dsThietBi.TBL_THIETBI.Rows.Count; i++)
                {
                    DataRow dr = dsThietBi.TBL_THIETBI.Rows[i];
                    if (dr.RowState == DataRowState.Modified)
                    {
                        object goc = dr["NoiSD", DataRowVersion.Original];
                        object moi = dr["NoiSD"];

                        if (goc == DBNull.Value)
                        {
                            if (moi != DBNull.Value)
                            {
                                TBL_DONVI ob = new TBL_DONVIDA().Get((int)moi);
                                if (ob != null)
                                {
                                    var lichsuDa = new TBL_lichsuDA();
                                    lichsuDa.Add(new TBL_lichsu
                                    {
                                        idthietbi = (int)dr["ID"],
                                        ngay = MyLogin.Original.Date,
                                        nguoiTH = MyLogin.Original.hoten,
                                        noidung = "Điều chuyển thiết bị đến " + ob.TenDonVi
                                    });

                                    if (SqlHelper.HasError)
                                    {
                                        MyBox.ShowWarning(SqlHelper.Message, "Quản lý thiết bị");
                                    }

                                }
                            }

                        }
                        else
                        {
                            if (moi != DBNull.Value)
                            {
                                int d = (int)moi - (int)goc;
                                if (d != 0)
                                {
                                    TBL_DONVI ob = new TBL_DONVIDA().Get((int)moi);
                                    if (ob != null)
                                    {
                                        var lichsuDa = new TBL_lichsuDA();
                                        lichsuDa.Add(new TBL_lichsu
                                        {
                                            idthietbi = (int)dr["ID"],
                                            ngay = MyLogin.Original.Date,
                                            nguoiTH = MyLogin.Original.hoten,
                                            noidung = "Điều chuyển thiết bị đến " + ob.TenDonVi
                                        });

                                        if (SqlHelper.HasError)
                                        {
                                            MyBox.ShowWarning(SqlHelper.Message, "Quản lý thiết bị");
                                        }

                                    }
                                }
                            }
                        }
                    }
                }


                tBL_THIETBITableAdapter.Adapter.RowUpdated += Adapter_RowUpdated;
                tBL_THIETBITableAdapter.Adapter.RowUpdating += Adapter_RowUpdating;
                tBL_THIETBITableAdapter.Update(dsThietBi.TBL_THIETBI);


                dsThietBi.TBL_THIETBI.AcceptChanges();
                NotSave = false;
            }
            catch (Exception ex)
            {
                MyBox.ShowWarning(ex.Message, "Quản lý thiết bị");
                //throw;
            }

            Mode = EditMode.None;
            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {

        }

        private void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {


            OnSaveChanging(new SaveChangingEventArgs(e.RowCount, dsThietBi.TBL_THIETBI.Count));
        }

        public override void Delete()
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iProvider)) return;

            if (MyBox.ShowQuestion("Bạn thật sự muốn xóa không?", "Quản lý thiết bị") == DialogResult.No) return;

            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            gcList.Enabled = false;
            var speedtimer = new Stopwatch();
            speedtimer.Start();

            NotSave = true;
            if (gbList.SelectedRowsCount > 0)
            {
                gbList.DeleteSelectedRows();
            }

            speedtimer.Stop();
            gcList.Enabled = true;
            OnSaveComplete(new SaveCompleteEventArgs(EditMode.Add, speedtimer.Elapsed.TotalSeconds));
            Cursor.Current = current;
        }

        public void Clear()
        {
            if (!TBL_quyenBL.isThaydoi(EnumComponent.iProvider)) return;
            if (MyBox.ShowQuestion("Bạn thật sự muốn xóa không?", "Quản lý thiết bị") == DialogResult.No) return;

            gbList.SelectAll();
            gbList.DeleteSelectedRows();
        }

        public void Previous()
        {
            gbList.MovePrev();
        }

        public void Next()
        {
            gbList.MoveNext();
        }

        private void gbList_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gbList.ClearColumnErrors();
            if (txtDonvi.Text.Length == 0)
            {
                MyBox.ShowWarning("Vui lòng chọn đơn vị!", "Quản lý thiết bị");
                return;
            }

            // gbList.UpdateCurrentRow();
            if (m_Column == Column.Lock) return;
            if (m_Column == Column.None)
            {
                if (e.Column == colTenTB) // | e.Column == colTenTB)
                {
                    m_Column = Column.MaTB;
                }
            }

            switch (m_Column)
            {
                case Column.None:
                    return;
                case Column.MaTB:
                    m_Column = Column.Lock;
                    gbList.SetRowCellValue(e.RowHandle, colMaDonVi, txtDonvi.EditValue);
                    if (dv != null) gbList.SetRowCellValue(e.RowHandle, colDiaChiIP, dv.IPClass);
                    //gbList.SetRowCellValue(e.RowHandle, colMaTB,TBL_THIETBIDA.NewID((int) txtDonvi.EditValue));
                    m_Column = Column.None;
                    return;
            }
        }

        private void gbList_RowUpdated(object sender, RowObjectEventArgs e)
        {
            //int rowindex = gbList.GetDataSourceRowIndex(e.RowHandle);
            //if (rowindex < 0 | rowindex > dsThietBi.TBL_THIETBI.Rows.Count)
            //   {
            //       gbList.UpdateCurrentRow();
            //        return;
            //   }
            //if (dsThietBi.TBL_THIETBI.Rows[rowindex].RowState == DataRowState.Added)
            {
                // Save();
            }
        }

        private void gbList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                Delete();
            }
        }

        private void gbList_DoubleClick(object sender, EventArgs e)
        {
            EquipHistory();
        }

        private void txtDonvi_EditValueChanged(object sender, EventArgs e)
        {
            if (txtDonvi.EditValue == null) return;
            if (NotSave)
            {
                DialogResult dialogResult = MyBox.ShowSave("Dữ liệu chưa được lưu!\nBạn có muốn lưu lại không?",
                                                           "Quản lý thiết bị");

                if (dialogResult == DialogResult.Cancel)
                {
                    return;
                }
                if (dialogResult == DialogResult.Yes)
                {
                    Save();
                }
            }
            NotSave = false;
            var da = new TBL_DONVIDA();
            dv = da.Get((int)txtDonvi.EditValue);
            Nap((int)txtDonvi.EditValue);
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F5:
                    NapInfo();
                    return true;
                case Keys.Control | Keys.S:
                    Save();
                    return true;
                case Keys.Control | Keys.W:
                    Save();
                    return true;
                case Keys.F2:
                    Save();
                    return true;
                case Keys.Alt | Keys.X:
                    Close();
                    return true;

                case Keys.F10:

                    Close();
                    return true;
            }

            return false;
        }

        private void gbList_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            int rowIndex = e.RowHandle;
            if (rowIndex >= 0)
            {
                rowIndex++;
                e.Info.DisplayText = rowIndex.ToString();
            }
        }

        private void DChiBHLookUpEdit_EditValueChanged(object sender, EventArgs e)
        {
            DiaChiBH.EditValue = DChiBHLookUpEdit.EditValue;
        }
    }
}